import requests
import time
from tool.config import read_config
from tool.weather import Weather
from tool import additional_information


class WeChat:
    def __init__(self, config_file_path):

        # 读取配置文件
        self.config = read_config(config_file_path)
        self.wechat_cfg = self.config["wechat_cfg"]
        self.user_inf = self.config["user_inf"]
        self.font_color = self.config["font_color"]
        self.notice_time = self.config["notice_time"]["notice_time"]
        self.weather_cfg = self.config["weather_cfg"]

        # 获取天气数据
        self.weather = Weather(self.weather_cfg)

    def get_weather(self):

        weather = Weather(self.weather_cfg)

        weather_data_dict = {
            "气温": weather.get_tem(),
            "平均风速": weather.get_speed(),
            "平均能见度": weather.get_visibility(),
            "空气质量": weather.get_air_quality(),
            "天气状态": weather.get_weather_condition()
        }

        return weather_data_dict

    # 获取每日情话

    def get_access_token(self):
        # 获取微信公众号接口token

        try:
            api = f'https://api.weixin.qq.com/cgi-bin/token?' \
                  f'grant_type=client_credential&' \
                  f'appid={self.wechat_cfg["app_id"]}&' \
                  f'secret={self.wechat_cfg["app_secret"]}'
            res = requests.get(api, timeout=90)

            if res.json()["access_token"]:
                re_token = res.json()["access_token"]
            else:
                print(f'获取Access_token失败\n原因:{res.json()["errmsg"]}')
                re_token = False

        except Exception as e:
            print(f'更新AccessToken错误,原因{e},请检查配置文件的appid/app_secret')
            re_token = False

        return re_token

    def send_msg(self):
        token = self.get_access_token()

        msg = {
            "touser": self.user_inf["open_id"],  # 推送对象ID

            "template_id": self.user_inf["template_id"],  # 模板ID
            "url": None,

            "topcolor": f"{self.font_color['top_color']}",  # 标题颜色

            "data": {

                "name": {

                    "value": f"{self.user_inf['user_name']} ",  # 对象名字

                    "color": f"{self.font_color['name_color']}"

                },

                "say": {

                    "value": additional_information.get_say(),  # 打招呼语

                    "color": f"{self.font_color['say_color']}"

                },

                "time_days": {
                    # 在一起多少天，天单位
                    "value": additional_information.get_love_total_duration(self.user_inf['together_time'])[0],

                    "color": f"{self.font_color['time_days_color']}"

                },

                "time_hours": {
                    # 小时单位
                    "value": f"{additional_information.get_love_total_duration(self.user_inf['together_time'])[1]}",

                    "color": f"{self.font_color['address_color']}"

                },

                "address": {

                    "value": f"{self.user_inf['address']}",  # 所在地名

                    "color": f"{self.font_color['weather_color']}"

                },

                "weather": {

                    "value": self.weather.weather_condition,  # 天气状态推送

                    "color": f"{self.font_color['weather_color']}"

                },

                "max_tem": {

                    "value": f'{self.weather.tem[0]} ℃',  # 最高气温

                    "color": f"{self.font_color['max_tem_color']}"

                },
                "min_tem": {

                    "value": f'{self.weather.tem[1]} ℃',  # 最低气温

                    "color": f"{self.font_color['min_tem_color']}"

                },
                "wind": {

                    "value": f'{self.weather.speed}',  # 风速

                    "color": f"{self.font_color['wind_color']}"

                },
                "visibility": {

                    "value": f'{self.weather.visibility}',  # 能见度

                    "color": f"{self.font_color['visibility_color']}"

                },
                "air_quality": {

                    "value": f'{self.weather.air_quality}',  # 空气质量

                    "color": f"{self.font_color['air_quality_color']}"

                },
                "notice": {
                    # 每日情话推送
                    "value": "我希望有个如你一般的人,如山间清爽的风;如古城温暖的阳光;从清晨到夜晚;从山野到书房,只要最后是你就好\n",

                    "color": f"{self.font_color['notice_color']}"

                },
                "my_name": {

                    "value": f"{self.user_inf['my_name']}",  # 我的名字

                    "color": f"{self.font_color['min_tem_color']}"

                },

                "other": {

                    "value": f"{self.user_inf['other_notice']}\n",  # 额外推送信息

                    "color": f"{self.font_color['other_color']}"

                },
                "birthday": {
                    # 推送对象多久生日
                    "value": f"{additional_information.get_birthday_days(self.user_inf['birthday'])}",

                    "color": f"{self.font_color['birthday_color']}"

                }

            }

        }

        try:
            res = requests.post(url=f"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={token}",
                                json=msg)

            if res.status_code != 200:
                print(f'服务器网络错误，代码:{res.status_code}')

            if res.json()["errcode"] == 0:
                print('>>>>>>>>>>>>>>>推送成功')
                return True

            elif res.json()["errcode"] == 40001:
                print('Access_Token失效')

            else:
                print(f'推送消息失败:{res.json()["errmsg"]}')

        except Exception as e:
            import traceback

            traceback.print_exc()
            print(e)


if __name__ == '__main__':
    WeChat(r"../config/parameter.cfg").send_msg()
